// 导入数据库
const db = require('../db/index')

// 对密码进行加密的包
const bcrypt = require('bcryptjs')

// 用来生成token字符串
const jwt = require('jsonwebtoken')

// 导入全局配置
const config = require('../config')

// 用户注册
exports.reguser = (req, res) => {
    const userInfo = req.body
    // 学生注册
    if (userInfo.id.length >= 11) {
        // 对密码进行加密
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        const sql = 'select * from student where id=?'
        zhuceHandler(req, res, sql, 'student', userInfo)
    // 老师注册
    } else if (11 > userInfo.id.length && userInfo.id.length > 3 ) {
        // 对密码进行加密
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        const sql2 = 'select * from teacher where id=?'
        zhuceHandler(req, res, sql2, 'teacher', userInfo)
        // 管理员注册
    } else {
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        const sql2 = 'select * from manager where id=?'
        zhuceHandler(req, res, sql2, 'manager', userInfo)
    }
}

// 注册函数
const zhuceHandler = (req, res, sql, user, userInfo) => {
    db.query(sql, userInfo.id, (err, results) => {
        if (err) return res.cc(err)
        if (results.length > 0) return res.cc('该学号被占用')
        // TODO: 新用户进行插入数据库
        const sql = `insert into ${user} set ?`
        db.query(sql, userInfo, (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 1) return res.cc('注册失败，请稍后再试！')
            res.cc('注册成功！', 0)
        })
    })
}

// 用户登录
exports.login = (req, res) => {
    const userInfo = req.body
    // 学生登录
    if (userInfo.id.length >= 11) {
        const sql = 'select * from student where id=? and username=?'
        loginHandler(req, res, sql, userInfo)
    // 老师登录
    } else if (11 > userInfo.id.length && userInfo.id.length > 3 ) {
        const sql2 = 'select * from teacher where id=? and username=?'
        loginHandler(req, res, sql2, userInfo)
        // 管理员登录
    } else {
        const sql3 = 'select * from manager where id=? and username=?'
        loginHandler(req, res, sql3, userInfo)
    }
}

// 登录函数
const loginHandler = (req, res, sql, userInfo) => {
    db.query(sql, [userInfo.id, userInfo.username], (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('学号或用户名错误！')
        // TODO：密码是否一致
        const comResult = bcrypt.compareSync(userInfo.password, results[0].password)
        if (!comResult) return res.cc('密码输入错误！')

        // TODO: 登录成功了
        // 剔除密码和头像
        const user = { ...results[0], password: '', user_pic: '' }
        // 生成token字符串
        const token = jwt.sign(user, config.jwtSecretKey, { expiresIn: '36h' })
        res.send({
            status: 0,
            message: '登录成功！',
            token: 'Bearer ' + token
        })
    })
}